import { capitalizeFirstLetter, dfsArray } from "@/utils";
import config from "@/configs/globalConfig";
//
// glob参数二配置
// eager 直接获取模块结果
// import: "default" 表示获取默认导出

/**
 * 自动创建路由
 * page.js views 文件夹每个路由的路由meta信息存放文件名
 * page.js 默认导出是当前目录的index.vue的meta信息
 * page.js 具名导出是当前目录下动态路由的meta信息 需与动态路由参数名一致
 * @param {string[]} filterFile 需要过滤的文件
 * @returns
 */
function autoCreateRoutes(filterFile = []) {
  const routes = [];
  const allModules = Object.entries(import.meta.glob("../views/**/*.vue"));
  const pageJS = import.meta.glob("../views/**/page.js", { eager: true });
  const metaInfo = {}; // 路由meta信息
  for (const key in pageJS) {
    let newKey = key.replace("/page.js", "");
    newKey = newKey.substring(newKey.lastIndexOf("/")).toLowerCase();
    metaInfo[newKey] = pageJS[key];
  }
  const dynamicRoute = []; // 存储动态路由

  for (const [filePath, module] of allModules) {
    // 当前页面的组件不做成路由
    if (
      filePath.includes("/comp/") ||
      filePath.includes("/components/") ||
      filterFile.some((v) => filePath.includes(`/${v}/`))
    ) {
      continue;
    }
    const path = filePath
      .replace("../views", "")
      .replace("index.vue", "")
      .toLowerCase(); // 路径
    const paths = path.split("/").filter(Boolean); // 路径数组
    let currentLevel = routes;
    for (let i = 0; i < paths.length; i++) {
      const part = paths[i];
      const requireArg = /^\[(.*)\].vue$/; // 匹配必选参数
      const optionalArg = /^\[\[(.*)\]\].vue$/; // 匹配可选参数
      let arg = "";
      let argName = "";

      const isLast = i === paths.length - 1;
      let existing = currentLevel.find((route) => route.path === `/${part}`);

      if (optionalArg.test(part)) {
        argName = optionalArg.exec(part)[1]; // 参数名
        arg = `:${argName}?`;
      } else if (requireArg.test(part)) {
        argName = requireArg.exec(part)[1]; // 参数名
        arg = `:${argName}`;
      }
      if (arg) {
        const parent = paths[i - 2]; // 父级路由
        dynamicRoute.push({
          parent,
          argName,
          arg,
          module,
          routerPath: paths[i - 1],
        });
        continue;
      }
      if (!existing) {
        existing = {
          path: part === "index" ? "/" : `/${part}`,
          name: capitalizeFirstLetter(part),
          component: module,
          children: [],
          meta:
            (part === "index"
              ? metaInfo["/index"]?.default
              : metaInfo[`/${part}`]?.default) ?? {},
        };
        currentLevel.push(existing);
      } else if (isLast) {
        // 如果是最后一部分且已存在，则更新 component
        existing.component = module;
      }
      currentLevel = existing.children;
    }
  }
  // 动态路由处理
  for (const item of dynamicRoute) {
    // parent父级路由 模块 动态参数名 路由路径 参数
    const { parent, module, argName, routerPath, arg } = item;
    const path = `/${routerPath}/${arg}`; // 路由路径
    const name =
      capitalizeFirstLetter(routerPath) + capitalizeFirstLetter(argName);
    if (!parent) {
      routes.push({
        path,
        name,
        component: module,
        meta: metaInfo[`/${routerPath}`]?.[argName] ?? {},
      });
    } else {
      dfsArray(routes, (route) => {
        if (route.path === `/${parent}`) {
          route.children.push({
            path,
            name,
            component: module,
          });
          return true;
        }
      });
    }
  }
  return routes;
}
const route = config.system.autoCreateRouter
  ? autoCreateRoutes(["Login", "404"])
  : [];
export default route;
